import axios, { AxiosResponse } from 'axios';

// 使用环境变量的安全方式
const getApiBaseUrl = () => {
  if (typeof window !== 'undefined') {
    // 浏览器环境
    return window.location.hostname === 'localhost' 
      ? 'http://localhost:8080/api/v1'
      : '/api/v1';
  }
  // 服务端环境或构建时
  return '/api/v1';
};

const API_BASE_URL = getApiBaseUrl();

import { useAuthStore } from '../stores/authStore';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 从localStorage获取token，因为拦截器中不能使用hooks
    const token = localStorage.getItem('auth-token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  (error) => {
    const { response } = error;
    
    if (response?.status === 401) {
      // Token过期或无效，清除认证状态
      localStorage.removeItem('auth-token');
      localStorage.removeItem('auth-user');
      
      // 避免在登录页面时重复跳转
      if (typeof window !== 'undefined' && !window.location.pathname.includes('/login')) {
        window.location.href = '/login';
      }
    } else if (response?.status === 403) {
      console.error('权限不足:', response.data?.message);
    } else if (response?.status === 404) {
      console.error('资源未找到:', response.data?.message);
    } else if (response?.status >= 500) {
      console.error('服务器错误:', response.data?.message);
    }
    
    return Promise.reject(error);
  }
);

// API响应类型定义
interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  data?: T;
  code?: number;
  timestamp?: string;
  requestId?: string;
}

// 通用API调用方法
class ApiService {
  // 解包后端响应数据
  private extractData<T>(response: any): T {
    // 如果响应有data字段且code为200，返回data内容
    if (response && typeof response === 'object' && response.code === 200 && response.data) {
      return response.data;
    }
    // 否则直接返回响应数据
    return response;
  }

  // GET请求
  async get<T>(url: string, params?: any, config?: any): Promise<T> {
    const response = await apiClient.get(url, { params, ...config });
    return this.extractData<T>(response.data);
  }

  // POST请求
  async post<T>(url: string, data?: any, config?: any): Promise<T> {
    const response = await apiClient.post(url, data, config);
    return this.extractData<T>(response.data);
  }

  // PUT请求
  async put<T>(url: string, data?: any): Promise<T> {
    const response = await apiClient.put(url, data);
    return this.extractData<T>(response.data);
  }

  // DELETE请求
  async delete<T>(url: string): Promise<T> {
    const response = await apiClient.delete(url);
    return this.extractData<T>(response.data);
  }

  // PATCH请求
  async patch<T>(url: string, data?: any): Promise<T> {
    const response = await apiClient.patch(url, data);
    return this.extractData<T>(response.data);
  }
}

export const apiService = new ApiService();
export default apiClient;